<?php
class Apps_Plugin_Upload_File {
	// MUST HAVE TRAILING BACKSLASH
	//const DEFAULT_UPLOAD_DIR = '/home/ohnew/public_html/public/upload/';
	//const DEFAULT_UPLOAD_URI = '/upload/';

	// For window
	const DEFAULT_UPLOAD_DIR = 'E:/Working/Home/Web/ohnew/public/upload/';
    const DEFAULT_UPLOAD_URI = '/upload/';

	// For linux
// 	const DEFAULT_UPLOAD_DIR = '/e/Working/Home/Web/ohnew/public/upload/';
//     const DEFAULT_UPLOAD_URI = '/upload/';

	const CAT_PRODUCT   = 'product';
	const CAT_ARTICLE 	= 'article';
	const CAT_EVENT 	= 'event';
	const CAT_GALLERY 	= 'gallery';
	const CAT_PRODUCT_CATEGORY   = 'product-category';


    // MUST HAVE TRAILING BACKSLASH
	public static $category = array(
	    self::CAT_PRODUCT   => 'product/',
	    self::CAT_ARTICLE 	=> 'article/',
	    self::CAT_EVENT		=> 'event/',
	    self::CAT_GALLERY   => 'gallery/',
	    self::CAT_PRODUCT_CATEGORY   => 'product-category/'
	);

	protected $_uploadDir  = self::DEFAULT_UPLOAD_DIR;
	protected $_uploadUri  = self::DEFAULT_UPLOAD_URI;
	protected $_subcat     = '';

	protected $_mode       = 0644;
	protected $_extension  = null; // array()
	protected $_mimetype   = null; // array()
	protected $_fileSize   = null; // array('min' => ?, 'max' => ?)

	protected $_maxQtty    = null; // int

	protected $_nameFormat = null; // Default nameFormat initialized in __construct

	protected $_allowOverwrite  = false;

	protected $_uploader;

	// @todo: Add options to arguments
	public function __construct() {
		$this->_nameFormat = create_function('$n', 'return uniqid() . \'_\' . $n;');
		$this->init();
	}
	protected function init(){}

	// SETTER
		public function setSubCategory($subcat) {
			if($subcat && isset(self::$category[$subcat])) {
			    $this->_subcat = self::$category[$subcat];
			}
			return $this;
		}
		public function setNameFormat($nameFormat) {
			$this->_nameFormat = $nameFormat;
			return $this;
		}
		public function setExtension($extension) {
			$this->_extension = $extension;
			return $this;
		}
		public function setMimetype($mimetype) {
			$this->_mimetype = $mimetype;
			return $this;
		}
		public function setMode($mode) {
			$this->_mode = $mode;
			return $this;
		}
		public function setFileSize($size) {
			$this->_fileSize = $size;
			return $this;
		}
		public function setMaxQuantity($qtty) {
			$this->_maxQtty = $qtty;
			return $this;
		}
		public function allowOverride($allowOveride) {
			if(null !== $allowOveride) {
				$this->_allowOverwrite = (bool) $allowOveride;
			}
			return $this;
		}

    // PROCESSING
	protected function _initUploader() {
        $uploader = new Zend_File_Transfer_Adapter_Http();
		if($this->_fileSize) {
		    $uploader->addValidator('Size', true, $this->_fileSize);
		}
        if($this->_extension) {
            $uploader->addValidator('Extension', false, $this->_extension);
        }
        if($this->_mimetype) {
            $uploader->addValidator('MimeType', true, $this->_mimetype);
        }

        return $this->_uploader = $uploader;
	}

	public function upload($subcat=null) {
        $uploaded = array();

		$this->_initUploader();
		$uploader       = $this->_uploader;

		if($subcat) { $this->setSubCategory($subcat); }
        $mode           = $this->_mode;
        $maxQtty        = $this->_maxQtty;
        $allowOverwrite = $this->_allowOverwrite;

        $uploadUri = $this->_uploadUri . $this->_subcat;
        $uploadDir = $this->_uploadDir . $this->_subcat;
        if(!is_dir($uploadDir)) {
        	if(!mkdir($uploadDir, '0777', true)) {
        		return $uploaded; /* FATAL ERROR */
        	}
        }

        $nameFormat = $this->_nameFormat;
        if(!is_callable($nameFormat)) {
	        if(is_string($nameFormat)) {
	        	$nameFormat = create_function('$n', 'return '. $nameFormat . ';');
	        } else {
	        	$nameFormat = create_function('$n', 'return $n;');
	        }
        }

        $counter = 0; // file uploaded counter
        $f = $uploader->getFileInfo();
        foreach ($f as $file => $info) {
            if(null !== $maxQtty && $maxQtty <= $counter) {
            	break;
            }

        	if($uploader->isValid($file)) {
        		$exName = self::unSign($info['name']);
            	$name   = $nameFormat($exName); // Rename
        		$path   = $uploadDir . $name;

        		// Disable Overwrite
        		if(!$allowOverwrite && file_exists($path)) {
        			continue;
        		}

        		//echo $path;
        		//Zend_Debug::dump($info);die;

        		$r = move_uploaded_file($info['tmp_name'], $path);

        		if($r) {
        			chmod($path, $mode);
	        		$uploaded[$file] = array(
	        		                      'exName' => $exName,
	        		                      'name'   => $name,

	        		                      'uri'    => $uploadUri . $name,
	        		                      'path'   => $uploadDir . $name,

	        		                      'dir'    => $uploadDir,
	        		                      'type'   => $info['type'],
	        		                      'size'   => $info['size']
	        		                   );
	        		++$counter;
        		}
        	}
        }

        return $uploaded;
	}

	public static function isUploaded($file) {
		return isset($_FILES[$file]) && $_FILES[$file]['tmp_name'];
	}
	public static function getPath($Uri, $uploadDir=self::DEFAULT_UPLOAD_DIR, $uploadUri=self::DEFAULT_UPLOAD_URI) {
		return $uploadDir . substr($Uri, strlen($uploadUri));
	}

	public function unSign ($str) {
		$str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $str);
		$str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $str);
		$str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $str);
		$str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $str);
		$str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str);
		$str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $str);
		$str = preg_replace("/(đ)/", 'd', $str);
		$str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $str);
		$str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $str);
		$str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $str);
		$str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $str);
		$str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $str);
		$str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $str);
		$str = preg_replace("/(Đ)/", 'D', $str);
		//$str = str_replace(" ", "-", str_replace("&*#39;","",$str));
		return $str;
	}
}